#include <string.h>

#include "sprite.h"

void sprite_blit(const sprite *src, sprite *dst, int x, int y)
{
    int x0, y0, width, height, i, j;
    unsigned char *src_data, *dst_data;

    // clip top-left
    x0 = x >= 0 ? 0 : -x;
    y0 = y >= 0 ? 0 : -y;

    // sprite is totally outside of destination's bounding box
    if ( x0 >= src->width || y0 >= src->height)
        return;

    // clip bottom-right
    width = x+src->width <= dst->width ? src->width-x0 : dst->width-x-x0;
    height = y+src->height <= dst->height ? src->height-y0 : dst->height-y-y0;

    // outside bounding box
    if ( width <= 0 || height <= 0)
        return;

    // initialize
    src_data = &src->data[x0+y0*src->width];
    dst_data = &dst->data[(x+x0)+(y+y0)*dst->width];

    // blit scanline-by-scanline
    for (i = 0; i < height; ++i, src_data += src->width, dst_data += dst->width)
        for (j = 0; j < width; ++j)
            dst_data[j] = src_data[j] == 255 ? dst_data[j] : src_data[j];
}
